/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.lock.service.redis;

import io.iec.edp.caf.lock.service.api.api.DistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wangyandong
 */
public class DistributedLockImpl implements DistributedLock {
    private RLock redLock;
    /**加锁资源*/
    private String resource;

    private boolean isLocked;

    /**
     * ctor
     * @param rLock
     */
    public DistributedLockImpl(String resource, RLock rLock){
        this.resource = resource;
        this.redLock = rLock;
    }

    public DistributedLockImpl(String resource, RLock rLock,boolean isLocked){
        this.resource = resource;
        this.redLock = rLock;
        this.isLocked=isLocked;
    }


    /**
     * 是否已正常获取锁
     * @return
     */
    @Override
    public boolean isAcquired() {
//        return this.redLock.isLocked();
        if (this.redLock != null&&this.redLock.isLocked()&& this.redLock.isHeldByCurrentThread()){
            return true;
        }else {
            return false;
        }

    }



    /**
     * 获取资源
     * @return 资源信息
     */
    @Override
    public String getResource() {
        return this.resource;
    }

    @Override
    public void close() {
        if(this.redLock!=null && this.redLock.isLocked()&&this.redLock.isHeldByCurrentThread()){
            this.redLock.unlock();
        }
    }

    @Override
    public void multiUnlock(){
        //mulilock的isLocked()及isHeldByCurrentThread()方法redisson都不支持
        if(this.redLock!=null){
            this.redLock.unlock();
        }
    }
}
